package com.vmove.childtrain.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.DragEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SlidingDrawer;

import com.vmove.childtrain.R;
import com.vmove.childtrain.activity.Lesson10Activity;
import com.vmove.childtrain.activity.Lesson11Activity;
import com.vmove.childtrain.activity.Lesson12Activity;
import com.vmove.childtrain.activity.Lesson12_NRActivity;
import com.vmove.childtrain.activity.Lesson13Activity;
import com.vmove.childtrain.activity.Lesson14Activity;
import com.vmove.childtrain.activity.Lesson15Activity;
import com.vmove.childtrain.activity.Lesson1Activity;
import com.vmove.childtrain.activity.Lesson2Activity;
import com.vmove.childtrain.activity.Lesson3Activity;
import com.vmove.childtrain.activity.Lesson4Activity;
import com.vmove.childtrain.activity.Lesson4_NRActivity;
import com.vmove.childtrain.activity.Lesson5Activity;
import com.vmove.childtrain.activity.Lesson6Activity;
import com.vmove.childtrain.activity.Lesson7Activity;
import com.vmove.childtrain.activity.Lesson8Activity;
import com.vmove.childtrain.activity.Lesson9Activity;
import com.vmove.childtrain.common.AppContext;
import com.vmove.childtrain.common.BaseFragment;
import com.vmove.childtrain.common.CustomSerialDriver;
import com.vmove.childtrain.db.dao.LightDao;
import com.vmove.childtrain.db.entity.Light;
import com.vmove.childtrain.protocol.CommandType;
import com.vmove.childtrain.protocol.LightCMD;
import com.vmove.childtrain.protocol.StatusCMD;
import com.vmove.childtrain.protocol.detail.LightCMD_Avoid_Conflict;
import com.vmove.childtrain.protocol.detail.LightCMD_Close_All;
import com.vmove.childtrain.protocol.detail.LightCMD_Open;
import com.vmove.childtrain.utils.UIUtils;
import com.vmove.childtrain.view.LightView;
import com.vmove.childtrain.view.LineWrapLayout;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class FirstFragment extends BaseFragment {

    @BindView(R.id.bt_lesson1)
    Button btLesson1;
    @BindView(R.id.bt_lesson2)
    Button btLesson2;
    @BindView(R.id.bt_lesson3)
    Button btLesson3;
    @BindView(R.id.bt_lesson4)
    Button btLesson4;
    @BindView(R.id.bt_lesson5)
    Button btLesson5;
    @BindView(R.id.bt_lesson6)
    Button btLesson6;
    @BindView(R.id.bt_lesson7)
    Button btLesson7;
    @BindView(R.id.bt_lesson8)
    Button btLesson8;
    @BindView(R.id.bt_lesson9)
    Button btLesson9;
    @BindView(R.id.bt_lesson10)
    Button btLesson10;
    @BindView(R.id.bt_lesson11)
    Button btLesson11;
    @BindView(R.id.bt_lesson12)
    Button btLesson12;
    @BindView(R.id.bt_lesson13)
    Button btLesson13;
    @BindView(R.id.bt_lesson14)
    Button btLesson14;
    @BindView(R.id.bt_lesson15)
    Button btLesson15;
    @BindView(R.id.bt_lesson16)
    Button btLesson16;
    @BindView(R.id.bt_lesson17)
    Button btLesson17;

    @BindView(R.id.lineWrapLayout)
    LineWrapLayout mLineWrapLayout;
    @BindView(R.id.handle)
    ImageView handle;
    @BindView(R.id.iv_on)
    ImageView ivOn;
    @BindView(R.id.iv_off)
    ImageView ivOff;
    @BindView(R.id.iv_refresh)
    ImageView ivRefresh;
    @BindView(R.id.slidingdrawer)
    SlidingDrawer slidingdrawer;

    CustomSerialDriver customSerialDriver;

    private List<Light> allLights;
    private LightDao lightDao;
    private HashMap<Integer, LightView> lightMap;

    @Override
    protected View loadView(LayoutInflater inflater) {
        View rootView = inflater.inflate(R.layout.fragment_first, null);
        return rootView;
    }

    @Override
    protected void bindView(View rootView) {
        lightMap = new HashMap<>();
        lightDao = new LightDao(mContext);
        try {
            allLights = lightDao.getAllLights();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (lightMap.isEmpty()){
            addLightsToView();
        }
        customSerialDriver = CustomSerialDriver.getInstance(AppContext.driver);
        slidingdrawer.setOnDrawerOpenListener(new SlidingDrawer.OnDrawerOpenListener() {
            @Override
            public void onDrawerOpened() {
                handle.setImageResource(R.drawable.handle_on);
            }
        });
        slidingdrawer.setOnDrawerCloseListener(new SlidingDrawer.OnDrawerCloseListener() {
            @Override
            public void onDrawerClosed() {
                handle.setImageResource(R.drawable.handle);
            }
        });
    }

    private void addLightsToView() {
        if (null != allLights && allLights.size() > 0) {
            for (int i = 0; i < allLights.size(); i++) {
                Light light = allLights.get(i);
                LightView lightView = new LightView(mContext);
                int lightSize = UIUtils.dip2px(100);//200
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(lightSize, lightSize);
                mLineWrapLayout.addView(lightView, i, layoutParams);
                lightMap.put(light.getLightId(), lightView);
            }
        }
    }

    @OnClick({R.id.bt_lesson1, R.id.bt_lesson2, R.id.bt_lesson3, R.id.bt_lesson4,R.id.bt_lesson5,R.id.bt_lesson6,R.id.bt_lesson7,
            R.id.bt_lesson8,R.id.bt_lesson9,R.id.bt_lesson10,R.id.bt_lesson14,R.id.handle, R.id.iv_on, R.id.iv_off, R.id.iv_refresh,
            R.id.bt_lesson11,R.id.bt_lesson12,R.id.bt_lesson13,R.id.bt_lesson15,R.id.bt_lesson16,R.id.bt_lesson17})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_lesson1:
                Intent intent1 = new Intent(getActivity(), Lesson1Activity.class);
                startActivity(intent1);
                getActivity().overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
                break;
            case R.id.bt_lesson2:
                Intent intent2 = new Intent(getActivity(), Lesson2Activity.class);
                startActivity(intent2);
                getActivity().overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
                break;
            case R.id.bt_lesson3:
                Intent intent3 = new Intent(getActivity(), Lesson3Activity.class);
                startActivity(intent3);
                getActivity().overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
                break;
            case R.id.bt_lesson4:
                Intent intent4 = new Intent(getActivity(), Lesson4Activity.class);
                startActivity(intent4);
                getActivity().overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
                break;
            case R.id.bt_lesson5:
                Intent intent5 = new Intent(getActivity(), Lesson5Activity.class);
                startActivity(intent5);
                getActivity().overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
                break;
            case R.id.bt_lesson6:
                Intent intent6 = new Intent(getActivity(), Lesson6Activity.class);
                startActivity(intent6);
                getActivity().overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
                break;
            case R.id.bt_lesson7:
                Intent intent7 = new Intent(getActivity(), Lesson7Activity.class);
                startActivity(intent7);
                getActivity().overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
                break;
            case R.id.bt_lesson8:
                Intent intent8 = new Intent(getActivity(), Lesson8Activity.class);
                startActivity(intent8);
                getActivity().overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
                break;
            case R.id.bt_lesson9:
                Intent intent9 = new Intent(getActivity(), Lesson9Activity.class);
                startActivity(intent9);
                getActivity().overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
                break;
            case R.id.bt_lesson10:
                Intent intent10 = new Intent(getActivity(), Lesson10Activity.class);
                startActivity(intent10);
                getActivity().overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
                break;
            case R.id.bt_lesson11:
                Intent intent11 = new Intent(getActivity(), Lesson11Activity.class);
                startActivity(intent11);
                getActivity().overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
                break;
            case R.id.bt_lesson12:
                Intent intent12 = new Intent(getActivity(), Lesson12Activity.class);
                startActivity(intent12);
                getActivity().overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
                break;
            case R.id.bt_lesson13:
                Intent intent13 = new Intent(getActivity(), Lesson13Activity.class);
                startActivity(intent13);
                getActivity().overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
                break;
            case R.id.bt_lesson14:
                Intent intent14 = new Intent(getActivity(), Lesson14Activity.class);
                startActivity(intent14);
                getActivity().overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
                break;
            case R.id.bt_lesson15:
                Intent intent15 = new Intent(getActivity(), Lesson15Activity.class);
                startActivity(intent15);
                getActivity().overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
                break;
            case R.id.bt_lesson16:
                Intent intent16 = new Intent(getActivity(), Lesson4_NRActivity.class);
                startActivity(intent16);
                getActivity().overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
                break;
            case R.id.bt_lesson17:
                Intent intent17 = new Intent(getActivity(), Lesson12_NRActivity.class);
                startActivity(intent17);
                getActivity().overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
                break;
            case R.id.handle:
                break;
            case R.id.iv_on:
                //点亮灯 1~8亮绿色  9~16亮蓝色
                for (Light light:allLights){
                    int lightId = light.getLightId();
                    if (lightId<9){
                        customSerialDriver.writeData(new LightCMD_Open().setLightColor(LightCMD.Color.GREEN.getByte())
                                .setShowNum(lightId).setLight(lightId).getBytes());
                    } else {
                        customSerialDriver.writeData(new LightCMD_Open().setLightColor(LightCMD.Color.BLUE.getByte())
                                .setShowNum(lightId-8).setLight(lightId).getBytes());
                    }
                }
                break;
            case R.id.iv_off:
                //熄灭灯
                for (Light id:allLights) {
                    customSerialDriver.writeData(new LightCMD().setLightColor(LightCMD.Color.NULL.getByte())
                            .setCheckMode(LightCMD.CheckMode.NULL.getByte()).setLight(id.getLightId()).getBytes());
                }
                break;
            case R.id.iv_refresh:
                getAllLightsStatus();
                break;
        }
    }

    /**
     * 查询所有灯状态 并 开启防冲突
     */
    private void getAllLightsStatus() {
        if (null==allLights || allLights.size()==0)
            return;
        final StatusCMD statusCMD = new StatusCMD();
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        customSerialDriver.writeData(new LightCMD_Avoid_Conflict().getBytes());
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        for (int i = 0; i <allLights.size(); i++) {
                            Light light = allLights.get(i);
                            statusCMD.setLight(light.getLightId());
                            customSerialDriver.writeData(statusCMD.getBytes());
                        }
                    }
                }
        ).start();
    }


    @Override
    public void setSerialReceivedData(byte[] data) {
        if (data.length<8) {
            return;
        }
        if (data[5] == CommandType.COMMAND_LIGHTSTATUS_R){//查询灯状态的回复
            //解析
            int light = data[4];
            int eLevel = data[9];
            LightView lightView = lightMap.get(light);
            Message message = mHandler.obtainMessage(MESSAGE_LIGHT_STATUS);
            message.arg1=light;
            message.sendToTarget();
            lightView.setElectricLevel(eLevel);
        }
    }

    public static final int MESSAGE_LIGHT_STATUS=3001;

   @SuppressLint("HandlerLeak")
   Handler mHandler = new Handler(){
       @Override
       public void handleMessage(Message msg) {
           switch (msg.what){
               case MESSAGE_LIGHT_STATUS:
                   int lightId = msg.arg1;
                   lightMap.get(lightId).setLightNumber(lightId);
                   break;
           }
           super.handleMessage(msg);
       }
   };
}
